<template>
  <div>
    <s-header :name='type === "edit" ? "编辑地址" : "新增地址"' />
    <van-address-edit
      :area-list="areaList"
      :address-info="addressInfo"
      show-delete
      show-set-default
      show-search-result
      detail-maxlength="500"
      tel-maxlength="11"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
    />
  </div>
</template>

<script>

import { Toast } from 'vant';
import { areaList } from '@vant/area-data';
import { saveAddress, deleteAddress, getAddressById } from '@/api/address';
import { mapGetters } from 'vuex';
import  sHeader  from '@/components/SHeader';


export default {
  name: 'addressEdit',
  data() {
    return {
      areaList,
      addressId: this.$route.query.addressId ? this.$route.query.addressId : null,
      type: this.$route.query.type ? this.$route.query.type : null,
      addressInfo: {},
      areaCode: ''
    }
  },
  created() {
    this.onload()
  },
  components: {
    sHeader,
  },
  computed: {
    ...mapGetters(['id'])
  },
  methods: {
    async onload() {

      if(this.addressId != null) {
        const { data: info } = await getAddressById(this.addressId)
        const province = Object.entries(this.areaList.province_list)
            Object.entries(this.areaList.county_list).forEach(([id, text]) => {
              if (text == info.countyName) {
                // 找到区对应的几个省份
                const provinceIndex =  province.findIndex(item => item[0].substr(0,2) == id.substr(0,2))
                // 找到区对应的几个市区
                // eslint-disable-next-line no-unused-vars
                const cityItem = Object.entries(this.areaList.city_list).filter(([cityId, cityName]) => cityId.substr(0, 4) == id.substr(0, 4))[0]
                // 对比找到的省份和接口返回的省份是否相等，因为有一些区会重名
                if (province[provinceIndex][1] == info.provinceName && cityItem[1] == info.cityName) {
                  this.areaCode = id
                }
                
              }
            })
            this.addressInfo = {
              id: info.id,
              name: info.userName,
              tel: info.userPhone,
              addressDetail: info.detailAddress,
              isDefault: info.defaultFlag,
              areaCode: this.areaCode
            }
      }
    },
    onSave(val) {
      if(val){
        saveAddress({
          userId: this.id,
          userName: val.name,
          userPhone: val.tel,
          provinceName: val.province,
          cityName: val.city,
          countyName:val.county,
          detailAddress: val.addressDetail,
          defaultFlag: val.isDefault
        }).then(res => {
          if(res.code === 200 && res.data == true) {
            Toast.success('保存成功');
            this.$router.go(-1);
          }
        })
      }
      
      
    },
    onDelete(val) {
      deleteAddress(val.id).then(res =>{
        if(res.code === 200){
          Toast.success('删除成功');
          this.$router.go(-1);
        }
      })
    },
    onClickLeft() {
      this.$router.go(-1)
    },
  }
}
</script>

<style>
  .block {
    height: 50px;
  }
</style>